package com.qfedu.order.service.Impl;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.qfedu.fmmall.entity.Orders;
import com.qfedu.order.config.MyPayConfig;
import com.qfedu.order.service.OrderTimeoutCanleService;
import com.qfedu.order.service.feign.OrderCloseClient;
import com.qfedu.order.service.feign.OrderStatusUpdateClient;
import com.qfedu.order.service.feign.OrderTimeoutQueryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderTimeoutCanleServiceImpl implements OrderTimeoutCanleService {

    private WXPay wxPay = new WXPay(new MyPayConfig());

    @Autowired
    private OrderCloseClient orderCloseClient;

    @Autowired
    private OrderStatusUpdateClient orderStatusUpdateClient;

    @Autowired
    private OrderTimeoutQueryClient orderTimeoutQueryClient;


    @Scheduled(cron = "0/60 * * * * ?")
    public void CheckAndCancleOrder() {
        System.out.println("开始读秒");
        try {
           //1.调用 order-timeout-query 查询超过10min订单依然为待支付的订单
            List<Orders> orders = orderTimeoutQueryClient.query();
            //2.访问微信平台接口，确认当前订单最终的支付状态
            for (int i = 0; i < orders.size(); i++) {
                Orders order = orders.get(i);
                HashMap<String,String> params = new HashMap<>();
                params.put("out_trade_no",order.getOrderId());
                //查询订单支付状态
                Map<String, String> orderQuery = wxPay.orderQuery(params);
                if("SUCCESS".equalsIgnoreCase(orderQuery.get("trade_state"))){
                    //如果支付成功，将订单修改为已支付/待发货
                    Orders updateOrder = new Orders();
                    updateOrder.setOrderId(order.getOrderId());
                    updateOrder.setStatus("2");
                    int j = orderStatusUpdateClient.update(updateOrder);
                }else if("NOPTPAY".equalsIgnoreCase(orderQuery.get("trade_state"))){
                    //未支付，取消订单
                    //1。先去微信平台关闭该订单的支付通道
                    Map<String, String> map = wxPay.closeOrder(params);
                    //2。关闭订单
                    orderCloseClient.close(order.getOrderId(),1);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
